package com.stylesmile.demo.aio.demo3;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;

public class AioAsyncHttpServer {
    private ByteBuffer byteBuffer;

    public static void main(String[] args) throws IOException {
        // 创建一个AsynchronousServerSocketChannel实例
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();

        // 将其绑定到指定的端口
        server.bind(new InetSocketAddress(8080));

        // 等待客户端连接
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel socket, Void attachment) {
                // 当客户端连接时，处理请求并发送响应
                handleRequest(socket);

                // 继续等待其他客户端连接
                server.accept(null, this);
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("Failed to accept a connection");
            }
        });

        // 阻塞主线程，以便服务器可以持续运行
        System.in.read();
    }

    private static void handleRequest(AsynchronousSocketChannel socket) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Future<Integer> readResult = socket.read(buffer);

        try {
            readResult.get();
            buffer.flip();

            // 构建HTTP响应
            String response = "HTTP/1.1 200 OK " +
                    "Content-Length: 13 " +
                    "Content-Type: text/plain " +
                    " " +
                    "Hello, World!";
            ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());

            // 将响应写入客户端
            Future<Integer> writeResult = socket.write(responseBuffer);
            writeResult.get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
